﻿/*******************************************************************************
 * Copyright © 2016 HDJ 版权所有
 * Website：http://www.lghy.com
 * Author: Luomg
 * CreateDate: 2021年1月25日
 * Description:
*********************************************************************************/

using System;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace System {

    /// <summary>
    /// 工具类
    /// </summary>
    public partial class Utils {
        public static T GetObjTranNull<T>(object obj) {
            try {
                var type = typeof(T);
                if(obj==null) {
                    return default(T);
                } else {
                    if(obj.GetType()==type)
                        return (T)obj;
                }
                if(type.IsEnum) {
                    if(obj is string) { return (T)Enum.Parse(type,obj as string); } else { return (T)Enum.ToObject(type,obj); }
                }
                if(type.IsGenericType&&type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
                    if(obj==null) { return default(T); }
                    type=Nullable.GetUnderlyingType(type);
                }
                return (T)System.Convert.ChangeType(obj,type,CultureInfo.InvariantCulture);
            } catch {
                if(typeof(T)==typeof(DateTime)) {
                    return (T)System.Convert.ChangeType("1900-01-01 00:00:00",typeof(T),CultureInfo.InvariantCulture);
                }
            }
            return default(T);
        }
        public static DateTime? GetObjTranNull(object obj) {
            if(obj==null) return null;
            try {
                return Convert.ToDateTime(obj.ToString());
            } catch {
                return null;
            }
        }
        public static string GetMapPath(string strPath) {
            strPath=strPath.Replace("/","\\").Replace("~/","").Replace("~\\","");
            if(strPath.StartsWith("\\")) {
                strPath=strPath.Substring(strPath.IndexOf('\\',1)).TrimStart('\\');
            }
            return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,strPath);
        }
        /// <summary>
        /// 在命令行窗口中执行
        /// </summary>
        public static void CmdStartCTIProc(string cmdStr) {
            using(Process process = new Process()) {
                process.StartInfo.FileName="cmd.exe";
                process.StartInfo.UseShellExecute=false;
                process.StartInfo.RedirectStandardInput=true;
                process.StartInfo.RedirectStandardOutput=true;
                process.StartInfo.RedirectStandardError=true;
                process.StartInfo.CreateNoWindow=true;
                process.Start();
                process.StandardInput.WriteLine(cmdStr+"&amp;exit");
                process.StandardInput.AutoFlush=true;
                string output = process.StandardOutput.ReadToEnd();
                Thread.Sleep(2000);
                process.WaitForExit();
                process.Close();
            }
        }
        public static void ApplicationExit() {
            CmdStartCTIProc("taskkill /f /im HDJ.ConsoleApp*");
            CmdStartCTIProc("taskkill /f /im phantomjs*");
            CmdStartCTIProc("taskkill /f /im conhost*");
        }
        public static string CreateImage(string text,bool isBold = false,int fontSize = 20) {
            int wid = 400;
            int high = 200;
            System.Drawing.Font font;
            if(isBold) {
                font=new System.Drawing.Font("Arial",fontSize,System.Drawing.FontStyle.Bold);
            } else {
                font=new System.Drawing.Font("Arial",fontSize,System.Drawing.FontStyle.Regular);
            }
            //绘笔颜色
            System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
            System.Drawing.StringFormat format = new System.Drawing.StringFormat(System.Drawing.StringFormatFlags.NoClip);
            format.Alignment=System.Drawing.StringAlignment.Center;
            format.LineAlignment=System.Drawing.StringAlignment.Center;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(wid,high);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.Clear(System.Drawing.Color.White);//透明

            System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0,0,wid,high);
            //绘制图片
            g.DrawString(text,font,brush,rect,format);
            //释放对象
            g.Dispose();

            string fileName = System.IO.Directory.GetCurrentDirectory()+"/pdfwatermark.png";
            image.Save(fileName,System.Drawing.Imaging.ImageFormat.Png);
            image.Dispose();

            return fileName;
        }


        #region 唯一订单号生成
        public static object _lock = new object();
        public static int count = 1;
        /// <summary>
        /// 唯一订单号生成
        /// </summary>
        public static string GenerateOrderNo(string prefix = "P") {
            lock(_lock) {
                if(count>=10000) {
                    count=1;
                }
                var number = prefix+DateTime.Now.ToString("yyyyMMddHHmmssfff")+count.ToString("0000");
                count++;
                return number;
            }
        }
        #endregion

        /// <summary>
        /// 读取字符串中的汉字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetChineseLetter(string str) {
            //str = "dfa#445发了,. 。*(*&*^e4444";
            string v = "";
            string pattern = @"^[\u300a\u300b]|[\u4e00-\u9fa5]|[\uFF00-\uFFEF]";
            if(Regex.IsMatch(str,pattern)) {
                //提示的代码在这里写
                Match m = Regex.Match(str,pattern);
                while(m.Success) {
                    if(m.Value==",") {
                        v+=m.Value;
                        continue;
                    }
                    v+=m.Value;
                    m=m.NextMatch();
                }
            }
            return v;
        }
        /// <summary>
        /// 向URL地址添加参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string AddParamToUrl(string url,string key,string value) {
            Regex reg = new Regex(@"^.*\?.+=.+$");
            if(reg.IsMatch(url)) {
                url+="&"+key+"="+value;
            } else {
                url+="?"+key+"="+value;
            }
            return url;
        }
    }
}